package com.lexue.articlesync.controller;

import com.lexue.articlesync.entity.Platform;
import com.lexue.articlesync.entity.PlatformAuth;
import com.lexue.articlesync.repository.PlatformRepository;
import com.lexue.articlesync.repository.PlatformAuthRepository;
import com.lexue.articlesync.service.CacheService;
import com.lexue.articlesync.service.ToutiaoCookiesService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.Map;
import java.util.HashMap;

/**
 * 平台管理API控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/platforms")
@RequiredArgsConstructor
public class PlatformController {
    
    private final PlatformRepository platformRepository;
    private final PlatformAuthRepository authRepository;
    private final CacheService cacheService;
    private final ToutiaoCookiesService toutiaoCookiesService;
    
    /**
     * 获取所有平台
     */
    @GetMapping
    public ResponseEntity<List<Platform>> getAllPlatforms() {
        List<Platform> platforms = platformRepository.findByEnabledTrueOrderBySortOrder();
        return ResponseEntity.ok(platforms);
    }
    
    /**
     * 根据内容类型获取支持的平台
     */
    @GetMapping("/by-type/{type}")
    public ResponseEntity<List<Platform>> getPlatformsByType(@PathVariable String type) {
        List<Platform> platforms = platformRepository.findByEnabledAndSupportedTypesContaining(type);
        return ResponseEntity.ok(platforms);
    }
    
    /**
     * 根据ID获取平台
     */
    @GetMapping("/{id}")
    public ResponseEntity<Platform> getPlatform(@PathVariable Long id) {
        Optional<Platform> platform = platformRepository.findById(id);
        return platform.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 创建平台
     */
    @PostMapping
    public ResponseEntity<Platform> createPlatform(@RequestBody PlatformRequest request) {
        try {
            Platform platform = Platform.builder()
                    .code(request.getCode())
                    .name(request.getName())
                    .description(request.getDescription())
                    .iconUrl(request.getIconUrl())
                    .websiteUrl(request.getWebsiteUrl())
                    .apiBaseUrl(request.getApiBaseUrl())
                    .supportedTypes(request.getSupportedTypes())
                    .enabled(request.getEnabled() != null ? request.getEnabled() : true)
                    .sortOrder(request.getSortOrder() != null ? request.getSortOrder() : 0)
                    .build();
            
            Platform savedPlatform = platformRepository.save(platform);
            
            log.info("平台创建成功: {}", savedPlatform.getName());
            return ResponseEntity.ok(savedPlatform);
            
        } catch (Exception e) {
            log.error("平台创建失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 更新平台
     */
    @PutMapping("/{id}")
    public ResponseEntity<Platform> updatePlatform(@PathVariable Long id, @RequestBody PlatformRequest request) {
        Optional<Platform> optionalPlatform = platformRepository.findById(id);
        if (!optionalPlatform.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            Platform platform = optionalPlatform.get();
            platform.setName(request.getName());
            platform.setDescription(request.getDescription());
            platform.setIconUrl(request.getIconUrl());
            platform.setWebsiteUrl(request.getWebsiteUrl());
            platform.setApiBaseUrl(request.getApiBaseUrl());
            platform.setSupportedTypes(request.getSupportedTypes());
            platform.setEnabled(request.getEnabled() != null ? request.getEnabled() : platform.getEnabled());
            platform.setSortOrder(request.getSortOrder() != null ? request.getSortOrder() : platform.getSortOrder());
            
            Platform savedPlatform = platformRepository.save(platform);
            
            log.info("平台更新成功: {}", savedPlatform.getName());
            return ResponseEntity.ok(savedPlatform);
            
        } catch (Exception e) {
            log.error("平台更新失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 删除平台
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deletePlatform(@PathVariable Long id) {
        if (!platformRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            platformRepository.deleteById(id);
            log.info("平台删除成功: {}", id);
            return ResponseEntity.ok().build();
            
        } catch (Exception e) {
            log.error("平台删除失败: {}", id, e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 获取平台的认证信息列表
     */
    @GetMapping("/{id}/auth")
    public ResponseEntity<List<PlatformAuth>> getPlatformAuth(@PathVariable Long id) {
        try {
            List<PlatformAuth> authList = authRepository.findByPlatformId(id);
            // 为每个认证信息手动加载平台信息
            authList.forEach(auth -> {
                if (auth.getPlatform() != null) {
                    // 触发懒加载
                    auth.getPlatform().getName();
                }
            });
             // 依据修改时间倒序
             authList.sort((a, b) -> b.getUpdatedAt().compareTo(a.getUpdatedAt()));
            return ResponseEntity.ok(authList);
        } catch (Exception e) {
            log.error("获取平台认证信息失败: {}", id, e);
            return ResponseEntity.ok(List.of());
        }
    }
    
    /**
     * 创建平台认证信息
     */
    @PostMapping("/{id}/auth")
    public ResponseEntity<PlatformAuth> createPlatformAuth(@PathVariable Long id, @RequestBody AuthRequest request) {
        Optional<Platform> optionalPlatform = platformRepository.findById(id);
        if (!optionalPlatform.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            Platform platform = optionalPlatform.get();
            
            PlatformAuth auth = PlatformAuth.builder()
                    .platform(platform)
                    .userIdentifier(request.getUserIdentifier())
                    .accessToken(request.getAccessToken())
                    .refreshToken(request.getRefreshToken())
                    .tokenExpiresAt(request.getTokenExpiresAt())
                    .extraAuthInfo(request.getExtraAuthInfo())
                    .cookies(request.getCookies())
                    .enabled(request.getEnabled() != null ? request.getEnabled() : true)
                    .status(PlatformAuth.AuthStatus.VALID)
                    .lastValidatedAt(LocalDateTime.now())
                    .build();
            
            PlatformAuth savedAuth = authRepository.save(auth);
            
            // 缓存认证信息
            cacheService.cacheAuth(platform.getCode(), request.getUserIdentifier(), savedAuth);
            
            log.info("平台认证信息创建成功: {} - {}", platform.getName(), request.getUserIdentifier());
            return ResponseEntity.ok(savedAuth);
            
        } catch (Exception e) {
            log.error("平台认证信息创建失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 更新平台认证信息
     */
    @PutMapping("/auth/{authId}")
    public ResponseEntity<PlatformAuth> updatePlatformAuth(@PathVariable Long authId, @RequestBody AuthRequest request) {
        Optional<PlatformAuth> optionalAuth = authRepository.findById(authId);
        if (!optionalAuth.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            PlatformAuth auth = optionalAuth.get();
            auth.setUserIdentifier(request.getUserIdentifier());
            auth.setAccessToken(request.getAccessToken());
            auth.setRefreshToken(request.getRefreshToken());
            auth.setTokenExpiresAt(request.getTokenExpiresAt());
            auth.setExtraAuthInfo(request.getExtraAuthInfo());
            auth.setCookies(request.getCookies());
            auth.setEnabled(request.getEnabled() != null ? request.getEnabled() : auth.getEnabled());
            auth.setLastValidatedAt(LocalDateTime.now());
            
            PlatformAuth savedAuth = authRepository.save(auth);
            
            // 更新缓存
            cacheService.cacheAuth(auth.getPlatform().getCode(), request.getUserIdentifier(), savedAuth);
            
            log.info("平台认证信息更新成功: {} - {}", auth.getPlatform().getName(), request.getUserIdentifier());
            return ResponseEntity.ok(savedAuth);
            
        } catch (Exception e) {
            log.error("平台认证信息更新失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 删除平台认证信息
     */
    @DeleteMapping("/auth/{authId}")
    public ResponseEntity<Void> deletePlatformAuth(@PathVariable Long authId) {
        Optional<PlatformAuth> optionalAuth = authRepository.findById(authId);
        if (!optionalAuth.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            PlatformAuth auth = optionalAuth.get();
            
            // 删除缓存
            cacheService.removeCachedAuth(auth.getPlatform().getCode(), auth.getUserIdentifier());
            
            authRepository.deleteById(authId);
            log.info("平台认证信息删除成功: {}", authId);
            return ResponseEntity.ok().build();
            
        } catch (Exception e) {
            log.error("平台认证信息删除失败: {}", authId, e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 头条平台：检测登录状态并获取cookies
     */
    @PostMapping("/toutiao/detect-cookies")
    public ResponseEntity<Map<String, Object>> detectToutiaoCookies() {
        try {
            ToutiaoCookiesService.CookiesResult result = toutiaoCookiesService.detectAndGetCookies();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", result.isSuccess());
            response.put("message", result.getMessage());
            
            if (result.isSuccess()) {
                response.put("cookies", result.getCookies());
                response.put("userInfo", result.getUserInfo());
                response.put("obtainedAt", result.getObtainedAt());
            } else if (result.getInstruction() != null) {
                response.put("instruction", result.getInstruction());
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("检测头条cookies失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "检测失败: " + e.getMessage());
            return ResponseEntity.ok(errorResponse);
        }
    }
    
    /**
     * 头条平台：验证cookies有效性
     */
    @PostMapping("/toutiao/validate-cookies")
    public ResponseEntity<Map<String, Object>> validateToutiaoCookies(@RequestBody Map<String, String> request) {
        try {
            String cookies = request.get("cookies");
            ToutiaoCookiesService.CookiesValidationResult result = 
                toutiaoCookiesService.validateCookiesWithUserInfo(cookies);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", result.isSuccess());
            response.put("valid", result.isValid());
            response.put("message", result.getMessage());
            
            if (result.isValid() && result.getUserInfo() != null) {
                response.put("userInfo", result.getUserInfo());
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("验证头条cookies失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "验证失败: " + e.getMessage());
            return ResponseEntity.ok(errorResponse);
        }
    }
    
    /**
     * 通用平台认证测试
     */
    @PostMapping("/{id}/test-auth")
    public ResponseEntity<Map<String, Object>> testPlatformAuth(@PathVariable Long id, @RequestBody Map<String, String> request) {
        try {
            Optional<Platform> optionalPlatform = platformRepository.findById(id);
            if (!optionalPlatform.isPresent()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "平台不存在");
                return ResponseEntity.ok(errorResponse);
            }
            
            Platform platform = optionalPlatform.get();
            
            // 根据平台类型进行不同的测试
            if ("toutiao".equals(platform.getCode())) {
                // 头条平台使用专用的cookies验证
                return testToutiaoAuth(request);
            } else {
                // 其他平台的通用测试
                return testGeneralPlatformAuth(platform, request);
            }
            
        } catch (Exception e) {
            log.error("测试平台认证失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "测试失败: " + e.getMessage());
            return ResponseEntity.ok(errorResponse);
        }
    }
    
    /**
     * 测试头条平台认证
     */
    private ResponseEntity<Map<String, Object>> testToutiaoAuth(Map<String, String> request) {
        try {
            String cookies = request.get("cookies");
            if (cookies == null || cookies.trim().isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "Cookies不能为空");
                errorResponse.put("needReconfig", true);
                return ResponseEntity.ok(errorResponse);
            }
            
            ToutiaoCookiesService.CookiesValidationResult result = 
                toutiaoCookiesService.validateCookiesWithUserInfo(cookies);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", result.isSuccess());
            
            if (result.isValid()) {
                response.put("userInfo", result.getUserInfo());
                response.put("message", "认证测试成功");
            } else {
                response.put("message", result.getMessage());
                response.put("needReconfig", true);
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("测试头条认证失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "测试失败: " + e.getMessage());
            errorResponse.put("needReconfig", true);
            return ResponseEntity.ok(errorResponse);
        }
    }
    
    /**
     * 测试通用平台认证
     */
    private ResponseEntity<Map<String, Object>> testGeneralPlatformAuth(Platform platform, Map<String, String> request) {
        try {
            String accessToken = request.get("accessToken");
            String cookies = request.get("cookies");
            
            // 这里可以按照具体平台的API进行验证
            // 目前先返回一个通用的模拟响应
            Map<String, Object> response = new HashMap<>();
            
            if ((accessToken != null && !accessToken.trim().isEmpty()) || 
                (cookies != null && !cookies.trim().isEmpty())) {
                
                // 模拟成功响应（实际应用中应该调用具体平台的API）
                response.put("success", true);
                response.put("message", "认证信息格式正确，但尚未实现真实的API验证");
                
                // 模拟用户信息
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("platform", platform.getName());
                userInfo.put("hasToken", accessToken != null && !accessToken.trim().isEmpty());
                userInfo.put("hasCookies", cookies != null && !cookies.trim().isEmpty());
                response.put("userInfo", userInfo);
                
            } else {
                response.put("success", false);
                response.put("message", "访问令牌和Cookies不能同时为空");
                response.put("needReconfig", true);
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("测试通用平台认证失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "测试失败: " + e.getMessage());
            errorResponse.put("needReconfig", true);
            return ResponseEntity.ok(errorResponse);
        }
    }
    
    /**
     * 头条平台：获取cookies配置指引
     */
    @GetMapping("/toutiao/cookies-instruction")
    public ResponseEntity<Map<String, Object>> getToutiaoCookiesInstruction() {
        ToutiaoCookiesService.CookiesResult result = toutiaoCookiesService.getCookiesFromBrowser();
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("instruction", result.getInstruction());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 平台请求DTO
     */
    public static class PlatformRequest {
        private String code;
        private String name;
        private String description;
        private String iconUrl;
        private String websiteUrl;
        private String apiBaseUrl;
        private String supportedTypes;
        private Boolean enabled;
        private Integer sortOrder;
        
        // Getters and Setters
        public String getCode() { return code; }
        public void setCode(String code) { this.code = code; }
        
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        
        public String getIconUrl() { return iconUrl; }
        public void setIconUrl(String iconUrl) { this.iconUrl = iconUrl; }
        
        public String getWebsiteUrl() { return websiteUrl; }
        public void setWebsiteUrl(String websiteUrl) { this.websiteUrl = websiteUrl; }
        
        public String getApiBaseUrl() { return apiBaseUrl; }
        public void setApiBaseUrl(String apiBaseUrl) { this.apiBaseUrl = apiBaseUrl; }
        
        public String getSupportedTypes() { return supportedTypes; }
        public void setSupportedTypes(String supportedTypes) { this.supportedTypes = supportedTypes; }
        
        public Boolean getEnabled() { return enabled; }
        public void setEnabled(Boolean enabled) { this.enabled = enabled; }
        
        public Integer getSortOrder() { return sortOrder; }
        public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; }
    }
    
    /**
     * 认证请求DTO
     */
    public static class AuthRequest {
        private String userIdentifier;
        private String accessToken;
        private String refreshToken;
        private LocalDateTime tokenExpiresAt;
        private String extraAuthInfo;
        private String cookies;
        private Boolean enabled;
        
        // Getters and Setters
        public String getUserIdentifier() { return userIdentifier; }
        public void setUserIdentifier(String userIdentifier) { this.userIdentifier = userIdentifier; }
        
        public String getAccessToken() { return accessToken; }
        public void setAccessToken(String accessToken) { this.accessToken = accessToken; }
        
        public String getRefreshToken() { return refreshToken; }
        public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; }
        
        public LocalDateTime getTokenExpiresAt() { return tokenExpiresAt; }
        public void setTokenExpiresAt(LocalDateTime tokenExpiresAt) { this.tokenExpiresAt = tokenExpiresAt; }
        
        public String getExtraAuthInfo() { return extraAuthInfo; }
        public void setExtraAuthInfo(String extraAuthInfo) { this.extraAuthInfo = extraAuthInfo; }
        
        public String getCookies() { return cookies; }
        public void setCookies(String cookies) { this.cookies = cookies; }
        
        public Boolean getEnabled() { return enabled; }
        public void setEnabled(Boolean enabled) { this.enabled = enabled; }
    }
}